const crypto = require('crypto');
const { pool } = require("../config/database");
const logger = require('../utils/logger');

class PasswordResetService {
  /**
   * 生成密码重置令牌
   * @param {string} email 用户邮箱
   */
  static async generateResetToken(email) {
    try {
      // 查询用户
      const [users] = await pool.query(
        'SELECT id, username, email FROM users WHERE email = ? AND status = 1',
        [email]
      );

      const user = users[0];
      if (!user) {
        throw new Error('用户不存在');
      }

      // 生成重置令牌
      const resetToken = crypto.randomBytes(32).toString('hex');
      const resetTokenExpires = new Date(Date.now() + 3600000); // 1小时后过期

      // 保存重置令牌
      await pool.query(
        'UPDATE users SET reset_token = ?, reset_token_expires = ? WHERE id = ?',
        [resetToken, resetTokenExpires, user.id]
      );

      return {
        userId: user.id,
        username: user.username,
        email: user.email,
        resetToken
      };
    } catch (error) {
      logger.error('生成密码重置令牌失败:', error);
      throw error;
    }
  }

  /**
   * 验证重置令牌
   * @param {string} token 重置令牌
   */
  static async verifyResetToken(token) {
    try {
      const [users] = await pool.query(
        'SELECT id FROM users WHERE reset_token = ? AND reset_token_expires > NOW() AND status = 1',
        [token]
      );

      if (!users.length) {
        throw new Error('重置令牌无效或已过期');
      }

      return users[0];
    } catch (error) {
      logger.error('验证重置令牌失败:', error);
      throw error;
    }
  }

  /**
   * 重置密码
   * @param {string} token 重置令牌
   * @param {string} newPassword 新密码
   */
  static async resetPassword(token, newPassword) {
    try {
      // 验证令牌
      const user = await this.verifyResetToken(token);

      // 更新密码并清除重置令牌
      await pool.query(
        'UPDATE users SET password = ?, reset_token = NULL, reset_token_expires = NULL WHERE id = ?',
        [newPassword, user.id]
      );

      return true;
    } catch (error) {
      logger.error('重置密码失败:', error);
      throw error;
    }
  }
}

module.exports = PasswordResetService; 